function el(id) { if (id == null || id == '') return null; return document.getElementById(id); }
function ev(id) {var e = el(id);if (e&&e.value) return e.value;return null;}
function nm(n){if(n==null||n=='') return null;return document.getElementsByName(n);}
function nmVal(n){var e=nm(n);if(e){for(var i=0;i<e.length;i++){if(e[i].checked)return e[i].value;}return null;}}
function Namespace(n) {parts = n.split('.'); var context = window; for (i = 0; i < parts.length; i++){if (!context[parts[i]])context[parts[i]] = {};context = context[parts[i]];}return context;}
function trim(s, c) { return ltrim(rtrim(s, c), c);}
function ltrim(s, c) { c= c || '\\s'; return s.replace(new RegExp('^['+c+']+', 'g'), '');}
function rtrim(s, c) {c= c || '\\s';return s.replace(new RegExp('['+c+']+$', 'g'), '');}
function seval(s){if(!s)return null;s=ltrim(s);if(s.length>0&&s.charAt(0)=='{')s=('('+s+')');return eval(s);}
function nonull(v){return v?v:''}
function round(n){return (Math.round(n*100)/100).toFixed(2);}
function Logout(a)
{
	var u=Web.Ajax.LoginUrl;
	if(a=='timeout')
		u=Web.Ajax.TimeoutUrl;
	location.href=u;
}
function SetClientTimeout()
{
	if(Web.Ajax.ClientTimeout)
	{
		if(Web.Ajax.ClientTimeoutId!=null)
			clearTimeout(Web.Ajax.ClientTimeoutId);
		Web.Ajax.ClientTimeoutId=setTimeout('Logout(\'timeout\');',Web.Ajax.ClientTimeout);
	}
};
if(window.top != window.self)
	SetClientTimeout();
function WebRequest(url, Target, xml, requestType)
{
	var u=url;var t=Target;var r;
	if(window.XMLHttpRequest)	r = new XMLHttpRequest(); 
	else if (window.ActiveXObject)	r = new ActiveXObject("Microsoft.XMLHTTP");
	this.Action=function()
	{
		if(r.readyState==4)
		{
			var e=r.getResponseHeader('Error');
			if(e=='MethodInvocation')
			{
				alert('Error calling Server side method:\n'+r.responseText)
				return;
			}
			if(e=='JsonConversion')
			{
				alert('Error converting response object to json:\n'+r.responseText)
				return;
			}
			if(e=='InvalidMethod')
			{
				alert('Cannot find static Server method:\n'+r.responseText)
				return;
			}
			if(e=='InvalidParameter')
			{
				alert('Invalid Parameter:\n'+r.responseText)
				return;
			}
			if(r.status == 302) {top.Logout(); return; }//Session is dead
			if(r.status == 12030) {top.Logout();return;}//Connection to server has been reset or terminated			
			if(r.status == 200 || r.status == 500)
			{
			    SetClientTimeout();
				var res=r.responseText;
				var time=r.getResponseHeader("MethodCallTime");
				if(t!=null)
				{
					var div=el(t);
					if(div!=null)
					{
						div.innerHTML=res;
						if(el(t+'_Time'))
							el(t+'_Time').innerHTML=time+'&nbsp;<b>secs</b>';
					}
					else
					{
						if (res.indexOf('Ajax:Logout()')!=-1) top.Logout();
						else t(seval(res));						
					}
				}
			}
			else
				alert('Error Making Request (Status: '+r.statusText+'), (Code: '+r.status + ')\n');
		}
	}
	var o=this;
	r.onreadystatechange = function(){o.Action();}
	r.open('POST', u, true);
	r.setRequestHeader('RequestType',requestType);
	r.send(xml);
}
//
function EncodeJson(s) {return s.replace(/'/g,'#APOS#') 
                                //*
                                .replace(/\\/g, "\\\\")
                                .replace(/\r/g, "\\r")
                                .replace(/\n/g, "\\n")
                                .replace(/\"/g, "\\\"") //*/
                                ;}
function DecodeJson(s) {return s.replace(/#APOS#/g,'\'')
                                //*
                                .replace(/\\\"/g,"\"")
                                .replace(/\\n/g,"\n")
                                .replace(/\\r/g,"\r")
                                .replace(/\\\\/g,"\\") //*/
                                ;}
/*/
function EncodeJson(s) {return s.replace(/\\/g, "\\\\")
                                .replace(/\r/g, "\\r")
                                .replace(/\n/g, "\\n")
                                .replace(/\"/g, "\\\"");}
function DecodeJson(s) {return s.replace(/\\\"/g,"\"")
                                .replace(/\\n/g,"\n")
                                .replace(/\\r/g,"\r")
                                .replace(/\\\\/g,"\\");}
/*/                                

function merge(o, no)
{
	if(!o)return no;
	if(!no)return o;
	for (var p in no)
	{
		var c = o[p];
		if (typeof c == 'object' && no[p] != null && !$.isArray(c))
			merge(o[p], no[p]);
		else
			o[p] = no[p];
	} 
	return o;
}
function ToJson(o)
{
	switch (typeof o) 
	{
		case 'string': return '\'' + EncodeJson(o) + '\'';
		case 'number': return String(o);
		case 'object': 
			if (o) 
			{
				var a = [];
				if (o.constructor == Array) 
				{
					for (var i = 0; i < o.length; i++) 
					{
						var json = ToJson(o[i])
						if (json != null) 
							a[a.length] = json
					}
					return '[' + a.join(',') + ']'
				}
				else if (o.constructor == Date){return 'new Date(' + o.getTime() + ')'}
				else
				{
					for (var p in o) 
					{
						var json = ToJson(o[p])
						if (json != null) a[a.length] = p + ':' + json
					}
					return '{' + a.join(',') + '}'
				}
			}
			return 'null';
		case 'boolean'  : return String(o);
		case 'function' : return;
		case 'undefined': return 'null';
	}
}
function FromJson(s){return seval(DecodeJson(s));}
function EncodeXml(s) { if (s == null) return null; return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;'); }
function Parameter(name,value,type){this.Name=name;this.Value=value;this.Type=type;}
function AjaxMethod(Url, Type, Name, Parameters, OnCompleted)
{
	var xml='<Call Type="'+Type+'" Name="'+Name+'">';
	for(i=0;i<Parameters.length;i++)
		xml+='<P Name="'+Parameters[i].Name+'" Type="'+Parameters[i].Type+'">'+EncodeXml(ToJson(Parameters[i].Value))+'</P>';
	xml+='</Call>';
	return new WebRequest(Url,OnCompleted,xml,'AjaxMethod');
}
function ResizeIFrame(iframe){if(iframe==null)return;iframe.style.height=iframe.contentWindow.document.documentElement.scrollHeight+'px';}
function DropDown(id, src, srcchanged)
{
	var This=this;
	var d=el(id);
	this.DropDown=d;
	this.Source=src;
	this.LoadingText='[Loading...]';
	var loading=false;
	this.Exists=function()
	{
		return d!=null;
	}
	this.GetValue=function()
	{
		if(!d)
			return null;
		var retVal=undefined;
		var idx=d.selectedIndex;
		if(d.options.length>idx&&idx>-1)
			retVal=d.options[d.selectedIndex].value;
		return retVal;
	}
	this.SetValue=function(v)
	{
		if(!d)
			return;
		d.selectedIndex=GetIndexForValue(d,v);
	}
	this.GetText=function(v)
	{
		if(!v)
			v=this.GetValue();
		return GetTextForValue(this.DropDown, v);
	}
	function GetIndexForValue(List,Value)
	{
		if(!List)
			return -1;
		for(i=0;i<List.options.length;i++)
		{
			if(List.options[i].value==Value)
				return i;
		}
		return -1;
	}
	function GetTextForValue(List,Value)
	{
		var Index=GetIndexForValue(List, Value);
		if(Index!=-1)
			return List.options[Index].text;
		return '';
	}
	this.SetDisabled=function(dis)
	{
		if(!d)
			return;
		d.disabled=dis;
	}
	this.SetDisplay=function(vis)
	{
		if(!d)
			return;
		d.style.display = vis;
	}
	this.OnChange=function(f)
	{
		if(!d)
			return;
		d.onblur=null;
		d.onkeypress=f;
		d.onchange=f;
		d.onclick=null;
	}
	this.SrcChanged=function()
	{
		if(!d)
			return;
		if(srcchanged&&!loading)
		{
			loading=true;
			d.options.length=0;
			d.options[0]=new Option(this.LoadingText,'');
			this.SetDisabled(true);
			if(src)
				src.SetDisabled(true);
			srcchanged(src.GetValue(), this.SrcChangedComplete);
		}
	}
	this.SrcChangedComplete=function(r)
	{
		loading=false;
		if(!r.Success)
		{
			if(This.Source)
				This.Source.SetDisabled(false);
			alert(r.Message)
			return;
		}
		if(r.Data)
		{
			This.DropDown.options.length=0;
			for(var i=0;i<r.Data.length;i++)
			{
				This.DropDown.options[This.DropDown.options.length]=new Option(r.Data[i].Text, r.Data[i].Value);
			}
			if(This.DropDown.onchange)
				This.DropDown.onchange();
			else
			{
				This.SetDisabled(false);
				This.Source.ChildSrcChangedComplete(false);
			}
		}
	}
	this.ChildSrcChangedComplete=function()
	{
		This.SetDisabled(false);
		if(This.Source)
			This.Source.ChildSrcChangedComplete();
	}
	if(src)
	{
		src.OnChange(function()
				{
					This.SrcChanged();
				}
			);
	}
}
function GetDocSize(win)
{
	if(!win)
		win=window
	var doc=win.document;
	var de=doc.documentElement;
	var _w=0;
	var _h=0;
	if(win.innerWidth)	//FireFox
	{
		_w=win.innerWidth-4;
		_h=win.innerHeight-4;
		if((de.scrollHeight-16)>_h)		//Long Page
		{
			_w=win.innerWidth-24;
			_h=de.scrollHeight-4;
		}
	}
	else					//IE
	{
		_w=doc.body.clientWidth;
		_h=doc.body.clientHeight;
		if(de.clientWidth>_w)			//Narrow Page
			_w=de.clientWidth;
		if(de.clientHeight>_h)			//Short Page
			_h = de.clientHeight;

	}
	return {w:_w,h:_h}
}
function Debug(s,x,y)
{
	var w=Append('div','DebugWindow', 'DebugWindow');	
	if(w)
	{
		if(w.style)
		{
			w.style.top=(y?y:0)+'px';
			w.style.left=(x?x:0)+'px';	
		}
		w.innerHTML+=ToJson(s)+'<br>';
		w.scrollTop=w.scrollHeight;
	}
}
function GetMouseCoords(e)
{
	if(e.pageX || e.pageY)
		return {x:e.pageX, y:e.pageY};
	return {x:(e.clientX + document.body.scrollLeft - document.body.clientLeft),y:(e.clientY + document.body.scrollTop  - document.body.clientTop)};
}
function GetPosition(o,s)
{
	if(!o)return null;
	var l=0,t=0,dl=0,dt=0;
	if(s)
	{
		if(s.indexOf('r')!=-1)
			dl+=o.offsetWidth;//dl+=o.clientWidth;
		if(s.indexOf('b')!=-1)
			dt+=o.offsetHeight;//dt+=o.clientHeight;
		if(s.indexOf('c')!=-1)
			dl+=o.offsetWidth/2;
		if(s.indexOf('m')!=-1)
			dt+=o.offsetHeight/2;
	}
		
	var n=o;
	while (n.offsetParent)
	{
		if(n.style.position=='absolute')
		{
			l+=parseInt(n.style.left.replace('px',''));
			t+=parseInt(n.style.top.replace('px',''));
			break;
		}
		l+= (n.offsetLeft - n.scrollLeft);t+= (n.offsetTop - n.scrollTop);
		/*var pn=t.parentNode;
		if(pn&&pn.tagName=='DIV'&&Web.Ajax.Browser=='FireFox')
		{
			//Account for scrollable divs
			l-=pn.scrollLeft;
			t-=pn.scrollTop;
		}*/
		n=n.offsetParent;
	}
	n=o;
	if (Web.Ajax.Browser != 'IE6' && Web.Ajax.Browser != 'IE7')//=='FireFox')
	{
		while (n.parentNode)
		{
			
			if(n.tagName=='DIV')
			{
				l-=n.scrollLeft;
				t-=n.scrollTop;
			}
			if(n.style.position=='absolute')
				break;
			n=n.parentNode;
		}
	}
	return {x:(l+dl), y:(t+dt)};
}
function GetPadding(o)
{
	if (!o) return null;
	s=o.style;
	var p = {};
	p.t = (s.paddingTop.indexOf('px') > 0) ? parseInt(s.paddingTop.replace(/px/g, '')) : 0;
	p.b = (s.paddingBottom.indexOf('px') > 0) ? parseInt(s.paddingBottom.replace(/px/g, '')) : 0;
	p.l = (s.paddingLeft.indexOf('px') > 0) ? parseInt(s.paddingLeft.replace(/px/g, '')) : 0;
	p.r = (s.paddingRight.indexOf('px') > 0) ? parseInt(s.paddingRight.replace(/px/g, '')) : 0;
	p.lr=p.l+p.r;
	p.tb=p.t+p.b;
	return p;
}
function GetSize(o)
{
	if (!o) return null;
	return {w:o.offsetWidth,h:o.offsetHeight};
}
function SetSize(o, w, h)
{
	if (!o) return null;
	var p=GetPadding(o);
	if (w != null)
		o.style.width = (w-p.lr) + 'px';
	if (h != null)
		o.style.height = (h-p.tb) + 'px';
}
function GetRec(o)
{
	var s=GetSize(o);
	return merge(s,GetPosition(o));
}
function Resize()
{
	var o=this;
	var ResizeObject;
	var LastMousePos = null;
	this.MouseMove=function(e)
	{
		if(!e)
			e=window.event;
		if(ResizeObject)
		{
			var m = GetMouseCoords(e);
			var s = GetSize(ResizeObject);
			var dw=m.x-LastMousePos.x;
			var dh=m.y-LastMousePos.y;
			var w=s.w+dw;
			var h=s.h+dh;
			if(w>0)
				ResizeObject.style.width=w+'px';
			if(h>0)
				ResizeObject.style.height=h+'px';
			LastMousePos=m;
			return false;
		}
	}
	this.MouseUp=function()
	{
		ResizeObject = null;
		document.onmousemove=null;
		document.onmouseup=null;
		var b=el('Modal_Background');
		if(b)
		{
			b.contentWindow.document.onmousemove=null;
			b.contentWindow.document.onmouseup=null;
		}
	}
	this.BeginResizing=function(t, e){ResizeObject=t;if(!e)e=window.event;LastMousePos  = GetMouseCoords(e);}
	this.MakeResizable=function(sid,tid)
	{
		if(tid==null)
			sid=tid;
		if(el(sid)==null||el(tid)==null)
			return;
		el(sid).onmousedown = function(e)
		{
			document.onmousemove=function(e){o.MouseMove(e);}
			document.onmouseup=function(e){o.MouseUp(e);}
			var b=el('Modal_Background');
			if(b)
			{
				//b.contentWindow.document.onmousemove=function(e){o.MouseMove(e);}
				//b.contentWindow.Resize=this;
				//b.contentWindow.document.onmouseup=function(e){Resize.Test();}
				b.contentWindow.document.onmousemove=function(e){o.MouseMove(e);}
				b.contentWindow.document.onmouseup=function(e){o.MouseUp(e);}
			}
			o.BeginResizing(el(tid), e);
			return false;
		}
	}
	this.Test=function()
	{
		alert('asdf');
	}
}
var Resize=new Resize();
function ElementIn(e,p)
{
	if(e)
	{
		while(e.parentNode)
		{
			if(e==p)
				return true;
			e=e.parentNode;
		}
	}
	return false;
}
function ElementInElementWithClass(e, cn)
{
	if (e && cn && cn!='')
	{
		while (e.parentNode)
		{
			if (e.className.indexOf(cn) != -1)
				return true;
			e = e.parentNode;
		}
	}
	return false;
}
function HoverBox(id)
{
	this.Set=function(t,v)
	{
		el(id).innerHTML=t;
		el(id+'_Text').value=t;
		el(id+'_Value').value=v;
	}
}
function IsFirefox()
{
	return navigator.userAgent.indexOf('Firefox')>0;
}
function ResourceUrl(n)
{
	return 'resource.axd?'+n;
}
function ImageUrl(n)
{
	return ResourceUrl(Web.Ajax.Style+'.'+n);
}
function ImageHtml(url, classname, click, help, id, style)
{
	if(url==null)
		return "";
	return '<img src="'+url+'" ' +
		(classname==null?'':'class="'+classname+'" ')+
		(style==null?'':'style="'+style+'" ')+
		(click==null?'':'onclick="'+click+'" ')+
		(help==null?'':'title="'+help+'" ')+
		(id==null?'':'id="'+id+'" ')+
		'>';
}
function ShowLoading(e)
{    
	var html='<table cellpadding="0" cellspacing="0" width="100%">';
	var h=e.clientHeight;
	var w=e.clientWidth;
	html+='<tr><td style="width:100%;height:'+h+'px;text-align:center;vertical-align:middle;"><img src="'+Web.Ajax.LoadingImg+'" /></td></tr>'
	html+='</table>'
	e.innerHTML=html;
}

//Save an object in a cookie
function SaveInCookie(n,o,d) //name, object, days
{
	var json=ToJson(o);
	if(json.length>3900)
		return;
	if (d) 
	{
		var date = new Date();
		date.setTime(date.getTime()+(d*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = n+"="+json+expires+"; path=/";
}

//Get an object from a cookie
function GetFromCookie(n) 
{
	var nameEQ = n + "=";
	var cs = document.cookie.split(';');
	for(var i=0;i < cs.length;i++) 
	{
		var c = cs[i];
		while (c.charAt(0)==' ') 
			c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) 
		{
			return FromJson(c.substring(nameEQ.length,c.length));
		}
	}
	return null;
}

//Delete an object stored in a cookie.
function DeleteInCookie(n) 
{
	SaveInCookie(n,"",-1);
}

function CookieSession()
{
}
var Session=GetFromCookie('ClientSession');
if(!Session)
	Session=new CookieSession();
function SaveSession(key,value)
{
	if(key)
		Session[key]=value;
	SaveInCookie('ClientSession',Session);
}
var base64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'.split("");
function base64(s)
{
	var r = ""; var p = ""; var c = s.length % 3; 
	if (c > 0) { for (; c < 3; c++) { p += '='; s += "\0"; } } 
	for (c = 0; c < s.length; c += 3) 
	{ 
		//if (c > 0 && (c / 3 * 4) % 76 == 0) { r += "\r\n"; }
		var n = (s.charCodeAt(c) << 16) + (s.charCodeAt(c+1) << 8) + s.charCodeAt(c+2);
		n = [(n >>> 18) & 63, (n >>> 12) & 63, (n >>> 6) & 63, n & 63];
		r += base64chars[n[0]] + base64chars[n[1]] + base64chars[n[2]] + base64chars[n[3]];
	}
	return r.substring(0, r.length - p.length) + p;
}
function encrypt(s)
{
	var r='';
	for(var i=0;i<s.length;i++)
		r+=String.fromCharCode(s.charCodeAt(i)^Web.Ajax.XorKey);
	return base64(r);
}
function param(k, v) {
	if (this == window)
		return new param(k,v);
	this.and = function(k, v) {
		if (!k)
			return this;
		this[k] = v;
		return this;
	}
	this.toString = function() {
		var q = '';
		for (var p in this) {
			if (typeof this[p] == 'function')
				continue;
			if (q.length > 1)
				q += '&';
			q += p;
			q += '=';
			var v=this[p];
			//if(v!=null&&v.constructor==Array)
			//	v=v.join();
			q += v;
		}
		return q;
	}
	this.qs = function() {
		return encrypt(this.toString());
	}
	return this.and(k, v);
}
function url(u) {
	if (this == window)
		return new url(u);
	u=u.replace(/~\//,Web.Ajax.AppBase);
	var pl = new param();
	this.p = function(k, v) {
		pl.and(k, v);
		return this;
	}
	this.ts = function() {
		var qs = pl.qs();
		if (!qs)
			return u;
		return u + '?' + pl.qs();
	}
	this.toString = function() {
		return this.ts();
	}
	this.go = function(fn) {
		if (fn) {
			var f = el(fn);
			if(f)
				f.src = this.toString();
		}
		else
			location.href = this.toString();
	}
	this.open = function () {
		window.open(this.toString());
	}
	return this;
}
(function($) {
	$.fn.enterPress = function(h) {
		this.each(function() {
			$(this).keypress(function(event) {
				var e = event;
				var keyCode;
				if (e)
					if (e.which)
					keyCode = e.which;
				else
					keyCode = e.keyCode;
				else keyCode = window.event.keyCode;
				if (keyCode == 13) {
					h();
					return false;
				}
			});
		});
	}
	$.fn.filterInput = function(re) {
		this.each(function() {
			$(this).keypress(function(event) {
				var e = event, key;
				if (e) {
					if (e.which) key = e.which;
					else return;
				} //key = e.keyCode; implies action key in FF
				else key = window.event.keyCode; //IE
				if (key == 8) return; //backspace
				var c = String.fromCharCode(key);
				if (!c.match(new RegExp(re))) return false;
			});
		});
	}
	$.fn.replaceSelection = function (s) {
		this.each(function() {
			if(this.selectionStart)
			{
				this.value = this.value.substr(0, this.selectionStart) + s + this.value.substr(this.selectionEnd, this.value.length);
				return;
			}
			if(document.selection)
			{
				this.focus();
				document.selection.createRange().text = s;
				return;
			}
			this.value+=s;
		});
	}
	$.fn.hider = function (u1, u2) {		
		if(u1)
			this.each(function(){$(this).attr('src', u1)});

		this.click(function(){
			$('#'+$(this).attr('hideid')).toggle('slow');
			if(u1&&u2)
			{
				var src=$(this).attr('src');				
				if(src==u1)
					$(this).attr('src', u2);
				if(src==u2)
					$(this).attr('src', u1);								
			}
		});
		return this;
	}
})(jQuery);
function insertAfter(element, target)
{
	if(!element)
		return;
	if(!target)
		target=document.body;
	var p = target.parentNode;
	if(p.lastchild == target) {p.appendChild(element);}
	else {p.insertBefore(element, target.nextSibling);}
}
function Append(t,id,c)
{
	var e=el(id);
	if(!e)
	{
		e=document.createElement(t);
		e.setAttribute("id", id);
		//Will throw error in ie6 if called before body tag closed.
		document.body.appendChild(e);
		e=el(id);
		if(c)
			e.className=c;
	}
	return e;
}

